package com.mali.common.web.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.mali.common.util.UserContext;
import com.mali.common.web.annotation.IgnoreAuthUserId;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Method;



@Slf4j
@AllArgsConstructor
public class GlobalAuthInterceptor implements HandlerInterceptor {

    private static final String USER_ID_HEADER = "userId";

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) {
        // 判断是否是放行api
        if (handler instanceof HandlerMethod handlerMethod) {
            // 判断控制器方法上是否有放行注解
            Method method = handlerMethod.getMethod();
            //  若有
            if (method.isAnnotationPresent(IgnoreAuthUserId.class)) {
                return true;
            }
            // 判断控制器类上是否有放行注解
            Class<?> type = handlerMethod.getBeanType();
            // 若有
            if (type.isAnnotationPresent(IgnoreAuthUserId.class)) {
                return true;
            }
        }

        // 从请求头中获取 userId
        String userIdStr = request.getHeader(USER_ID_HEADER);

        if (StrUtil.isBlank(userIdStr)) {
            log.warn("[鉴权失败] 请求头中缺少 userId");
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }

        Long userId = Convert.toLong(userIdStr, null);
        if (userId == null || userId <= 0) {
            log.warn("[鉴权失败] userId 非法: {}", userIdStr);
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }

        // 保存到 ThreadLocal 中
        UserContext.setUserId(userId);
        log.info("[鉴权成功] 当前用户 ID: {}", userId);
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request,
                                @NotNull HttpServletResponse response,
                                @NotNull Object handler,
                                Exception ex) {
        // 清理上下文，防止内存泄漏
        UserContext.removeUserId();
    }
}
